<template>
  <div class="login-container">
    <el-form :hidden="login" ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form"
             auto-complete="on"
             label-position="left">

      <div class="title-container">
        <h3 class="title">用户登录</h3>
      </div>

      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user"/>
        </span>
        <el-input
          v-model="loginForm.username"
          placeholder="请输入用户名"
          name="username"
          type="text"
          tabindex="1"
          auto-complete="on"
        />
      </el-form-item>

      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password"/>
        </span>
        <el-input
          :key="passwordType"
          ref="password"
          v-model="loginForm.password"
          :type="passwordType"
          placeholder="请输入密码"
          name="password"
          tabindex="2"
          auto-complete="on"
          @keyup.enter.native="handleLogin"
        />
        <span class="show-pwd" @click="showPwd">
          <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"/>
        </span>
      </el-form-item>
      <el-image :src="codeUrl" @click="refreshCode" class="imgCode"/>
      <el-form-item prop="code" style="width: 70%;float: right;">
        <el-input
          ref="code"
          v-model="loginForm.code"
          type="text"
          name="code"
          tabindex="2"
          auto-complete="on"
        />
      </el-form-item>
      <el-row>
        <el-col :span="12" style="text-align: center">
          <el-button :loading="loading" type="primary" @click.native.prevent="handleLogin"
                     style="width: 56%;margin-button: 20px">登录
          </el-button>
        </el-col>
        <el-col :span="12">
          <el-link @click="doPhone()">
            <el-button style="margin-button: 20px">手机号登录</el-button>
          </el-link>
        </el-col>
      </el-row>
    </el-form>
    <!--手机号登录-->
    <el-form class="login-form" auto-complete="on" :hidden="reg" label-position="left"
             :rules="rules" :model="loginForm.loginPhone">
      <div class="title-container">
        <h3 class="title">手机号登录</h3>
      </div>
      <el-form-item prop="phone" >
        <span class="svg-container">
          <i class="el-icon-phone"/>
        </span>
        <el-input
          ref="phone"
          v-model="loginForm.loginPhone.phone"
          placeholder="请输入手机号"
          name="phone"
          type="text"
          tabindex="1"
          auto-complete="on"
        />
      </el-form-item>
      <el-row>
        <el-col :span="12" style="width: 20%;margin-top: 5px">
          <el-button @click="doSend" :disabled="sendDis">{{timeInfo}}</el-button>
        </el-col>
        <el-col :span="12"style="width: 70%;float: right">
          <el-form-item prop="phonecode">
            <el-input
              ref="phonecode"
              v-model="loginForm.loginPhone.phonecode"
              placeholder="请输入验证码"
              name="phonecode"
              type="text"
              tabindex="1"
              auto-complete="on"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12" style="text-align: center">
          <el-button :loading="loading" type="primary" @click="handleLogin"
                     style="width: 50%;margin-button: 20px;display: inline">登录
          </el-button>
        </el-col>
        <el-col :span="12">
          <el-button :loading="loading" type="info" @click="fan"
                     style="width: 50%;margin-button: 20px;display: inline">返回
          </el-button>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import {sendPhone,loginPhonelzq} from '@/api/user'
  export default {
    name: 'Login',
    data() {
      const validateUsername = (rule, value, callback) => {
        if (value == '') {
          callback(new Error('请输入正确的用户名'))
        } else {
          callback()
        }
      }
      const validatePassword = (rule, value, callback) => {
        if (value.length < 4) {
          callback(new Error('密码不能少于6位'))
        } else {
          callback()
        }
      }
      const validateCode = (rule, value, callback) => {
        if (value == '') {
          callback(new Error('请输入验证码'))
        } else {
          callback()
        }
      }
      const validatePhone = (rule, value, callback) => {
        if (value == null ) {
          callback(new Error('哥们别忘了手机号'))
        } else {
          callback()
        }
      }
      const validatePhonecode = (rule, value, callback) => {
        if (value == ''||value==null) {
          callback(new Error('哥们别忘了验证码'))
        } else {
          callback()
        }
      }
      return {
        //手机号登录
        loginPhone:{
          //手机号验证码
          phonecode: '',
          //手机号
          phone: null,
        },
        //按钮文字
        timeInfo:'发送验证码',
        //验证码倒计时
        timePhone:60,
        //是否禁用发送短信按钮
        sendDis:false,
        //手机号登录页面
        reg: true,
        //登录页面
        login: false,
        //图片验证码获取地址
        codeUrl: 'http://localhost:8001/tbUser/captcha',
        loginForm: {
          username: '',
          password: '',
          code: '',
          loginPhone:{
            //手机号验证码
            phonecode: '',
            //手机号
            phone: null,
          }
        },
        loginRules: {
          username: [{required: true, trigger: 'blur', validator: validateUsername}],
          password: [{required: true, trigger: 'blur', validator: validatePassword}],
          code: [{required: true, trigger: 'blur', validator: validateCode}],
        },
        rules:{
          phonecode: [{required: true, trigger: 'blur', validator: validatePhonecode}],
          phone: [{required: true, trigger: 'blur', validator: validatePhone}]
        },
        loading: false,
        passwordType: 'password',
        redirect: undefined
      }
    },
    watch: {
      $route: {
        handler: function (route) {
          this.redirect = route.query && route.query.redirect
        },
        immediate: true
      }
    },
    methods: {
      //发送验证码
      doSend(){
        var $this=this
        sendPhone($this.loginForm.loginPhone.phone).then(res=>{
          alert("发送成功！注意查收，有效期60秒！");
          $this.sendDis=true;
          let inter=setInterval(function () {
            $this.timeInfo=$this.timePhone+'秒'
            --$this.timePhone;
            if($this.timePhone<0){
              $this.timeInfo='重新发送';
              $this.timePhone=60;
              $this.sendDis=false;
              window.clearInterval(inter);
            }
          },1000)

        }).catch(error=>{
          console.log(error+"手机号出错了！")
        })
      },
      //手机号登录页面切换
      doPhone() {
        this.reg = false
        this.login = true;
      },
      //手机号登录按钮
      loginPhoneD(){
        this.$store.dispatch("user/loginPh",this.loginPhone).then(() => {
          this.$router.push({path: this.redirect || '/'})
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
        //loginPhonelzq(this.loginPhone.phone,this.loginPhone.phonecode)
        // this.$refs.loginPhone.validate(valid=>{
        //   alert(valid)
        //   if(valid){
        //     alert("手机号登录！")
        //   }
        // })
      },
      //返回密码登录界面
      fan() {
        this.reg = true
        this.login = false;
      },
      refreshCode() {
        const num = Math.ceil(Math.random() * 10) // 生成一个随机数（防止缓存）
        this.codeUrl = 'http://localhost:8001/tbUser/captcha?' + num;
      },
      showPwd() {
        if (this.passwordType === 'password') {
          this.passwordType = ''
        } else {
          this.passwordType = 'password'
        }
        this.$nextTick(() => {
          this.$refs.password.focus()
        })
      },
      handleLogin() {
        this.$refs.loginForm.validate(valid => {
          if (valid) {
            this.loading = true
            this.$store.dispatch('user/login', this.loginForm).then(() => {
              this.$router.push({path: this.redirect || '/'})
              this.loading = false
            }).catch(() => {
              this.loading = false
            })
          } else {
            //标志修改
            this.loading = true
            this.$store.dispatch('user/login', this.loginForm).then(() => {
              this.$router.push({path: this.redirect || '/'})
              this.loading = false
            }).catch(() => {
              this.loading = false
            })
            // console.log('error submit!!')
            // return false
          }
        })
      }
    }
  }
</script>

<style lang="scss">
  .imgCode {
    cursor: pointer;
  }

  /* 修复input 背景不协调 和光标变色 */
  /* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

  $bg: #283443;
  $light_gray: #fff;
  $cursor: #fff;

  @supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
    .login-container .el-input input {
      color: $cursor;
    }
  }

  /* reset element-ui css */
  .login-container {
    .el-input {
      display: inline-block;
      height: 47px;
      width: 85%;

      input {
        background: transparent;
        border: 0px;
        -webkit-appearance: none;
        border-radius: 0px;
        padding: 12px 5px 12px 15px;
        color: $light_gray;
        height: 47px;
        caret-color: $cursor;

        &:-webkit-autofill {
          box-shadow: 0 0 0px 1000px $bg inset !important;
          -webkit-text-fill-color: $cursor !important;
        }
      }
    }

    .el-form-item {
      border: 1px solid rgba(255, 255, 255, 0.1);
      background: rgba(0, 0, 0, 0.1);
      border-radius: 5px;
      color: #454545;
    }
  }
</style>

<style lang="scss" scoped>
  $bg: #2d3a4b;
  $dark_gray: #889aa4;
  $light_gray: #eee;

  .login-container {
    min-height: 100%;
    width: 100%;
    background-color: $bg;
    overflow: hidden;

    .login-form {
      position: relative;
      width: 520px;
      max-width: 100%;
      padding: 160px 35px 0;
      margin: 0 auto;
      overflow: hidden;
    }

    .tips {
      font-size: 14px;
      color: #fff;
      margin-bottom: 10px;

      span {
        &:first-of-type {
          margin-right: 16px;
        }
      }
    }

    .svg-container {
      padding: 6px 5px 6px 15px;
      color: $dark_gray;
      vertical-align: middle;
      width: 30px;
      display: inline-block;
    }

    .title-container {
      position: relative;

      .title {
        font-size: 26px;
        color: $light_gray;
        margin: 0px auto 40px auto;
        text-align: center;
        font-weight: bold;
      }
    }

    .show-pwd {
      position: absolute;
      right: 10px;
      top: 7px;
      font-size: 16px;
      color: $dark_gray;
      cursor: pointer;
      user-select: none;
    }
  }
</style>
